package com.sita.bike.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.sita.bike.R;
import com.sita.bike.beans.PersonBean;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Location;
import com.sita.bike.rest.model.RegisterRequestParams;
import com.sita.bike.rest.model.RegisterResponseData;
import com.sita.bike.rest.model.RestResponse;
import com.sita.bike.rest.model.UpdateAccountParams;
import com.sita.bike.support.LocationController;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.BitmapUtils;
import com.sita.bike.utils.LocalStorage;
import com.sita.bike.utils.PersistUtils;
import com.sita.bike.utils.PhoneUtils;
import com.sita.bike.utils.RetrofitUtils;
import com.sita.bike.utils.ValidateUtils;
import com.sita.friend.FriendHelper;
import com.sita.friend.ui.activity.MainActivity;

import java.io.File;
import java.util.Date;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

/**
 * Class RegisterActivity is for
 *
 * @author xiaodong on 15/3/2.
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private Toolbar mToolbar;
    private EditText mMobileEdit;
    private EditText mPasswordEdit;
    private EditText mConfirmPasswordEdit;
    private EditText mNickNameEdit;
    private Button mRegisterBtn;

    private PersonBean personBean;
    @Bind(R.id.login)
    public TextView tv_login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initViews();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initViews() {
        mRegisterBtn = (Button) findViewById(R.id.register_button);
        mRegisterBtn.setOnClickListener(this);
        mNickNameEdit = (EditText) findViewById(R.id.register_nickname);
        mMobileEdit = (EditText) findViewById(R.id.register_et_mobile);
        mPasswordEdit = (EditText) findViewById(R.id.register_et_pwd);
        mConfirmPasswordEdit = (EditText) findViewById(R.id.register_et_pwd_confirm);
        mMobileEdit.setError(null);
        mPasswordEdit.setError(null);
        mMobileEdit.requestFocus();
    }

    private void attemptRegister() {

        String nick = mNickNameEdit.getText().toString();
        String mobile = mMobileEdit.getText().toString();
        String password = mPasswordEdit.getText().toString();
        String confirmPassword = mConfirmPasswordEdit.getText().toString();
        if (mobile.length() > 11) {
            mobile = mobile.substring(0, 11);
            mMobileEdit.setText(mobile);
        }
        if (!ValidateUtils.checkMobile(mobile)) {
            mMobileEdit.setError(getString(R.string.error_invalid_mobile));
            mMobileEdit.requestFocus();
            return;
        }
        if (!ValidateUtils.checkPassword(password)) {
            mPasswordEdit.setError(getString(R.string.error_invalid_password));
            mPasswordEdit.requestFocus();
            return;
        }
        if (!ValidateUtils.checkPassword(confirmPassword)) {
            mConfirmPasswordEdit.setError(getString(R.string.error_invalid_password));
            mConfirmPasswordEdit.requestFocus();
            return;
        }
        if (password.compareTo(confirmPassword) != 0) {
            mConfirmPasswordEdit.setError(getString(R.string.error_mismatch_password));
            mConfirmPasswordEdit.requestFocus();
            return;
        }

        PersistUtils.clearDatabase(); // why clear? // TODO: 2016/3/15  

        personBean = new PersonBean();
        personBean.person.setName(nick);
        personBean.person.setMobile(mobile);
        personBean.person.setName(mobile);
        personBean.pushDeviceId = PhoneUtils.getDeviceId();
        personBean.pushToken = PhoneUtils.getDeviceToken();
        personBean.password = password;

// TODO: 2016/1/15 now no need to check push deviceid & token
//        if (TextUtils.isEmpty(personBean.pushDeviceId) || TextUtils.isEmpty(personBean.pushToken)) {
//            Crouton.makeText(this, R.string.NETWORK, Style.ALERT).show();
//            return;
//        }

        final MaterialDialog dialog = new MaterialDialog.Builder(this).title(R.string.user_register).content(R.string.registering)
                .progress(true, 15000)
                .build();
        dialog.show();

        RegisterRequestParams paramsJson = new RegisterRequestParams();
        paramsJson.mMobile = personBean.person.getMobile();
        paramsJson.mNickname = personBean.person.getName();
        paramsJson.mPassword = personBean.password;
        paramsJson.mLocation = new Location();
        AMapLocation loc = LocationController.getLastKnownLocation();
        if (loc != null) {
            paramsJson.mLocation.latitude = String.valueOf(loc.getLatitude());
            paramsJson.mLocation.longitude = String.valueOf(loc.getLongitude());
        }

        String p = RestClient.getGson().toJson(paramsJson);
        TypedString params = new TypedString(p);

        RestClient.getRestService().register(params, new Callback<RestResponse>() {
                    @Override
                    public void success(RestResponse registerResponse, Response response) {
                        dialog.dismiss();

                        if (response.getStatus() == 200) {
                            if (registerResponse.mErrorCode.equals("0")) {
//                    personBean.credential.setUuid(regResp.tokenMap.uuid);
                                RegisterResponseData data;
                                String jsonstr = RestClient.getGson().toJson(registerResponse.mData);
                                data = RestClient.getGson().fromJson(jsonstr, RegisterResponseData.class);

                                personBean.credential.setToken(data.mToken);
                                personBean.credential.setXmppUser(data.mImId);
                                personBean.credential.setXmppPass(data.mImPwd);
                                personBean.credential.setLastLoginTime(new Date());
                                personBean.pushDeviceId = PhoneUtils.getDeviceId();
                                personBean.pushToken = PhoneUtils.getDeviceToken();
                                personBean.person.setAvatarUrl(data.mAvatar);

                                // EASY
                                // 保存用户名
                                FriendHelper.getInstance().setCurrentUserName(data.mImId);

//                                // After Regist Ok, the head will set to default and save
//                                Bitmap head = ((BitmapDrawable) getResources().getDrawable(R.drawable.ic_default_head)).getBitmap();
//                                personBean.person.setPhoto(BitmapUtils.bitmapToBytes(head));
//                                attemptUpdate(head);

                                registerSuccess();
                            } else {
                                Toast.makeText(RegisterActivity.this, (String) registerResponse.mData, Toast.LENGTH_SHORT).show();
                                registerFailed();
                            }

                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        dialog.dismiss();
                        RetrofitUtils.displayError(RegisterActivity.this, error);
                        registerFailed();
                        Toast.makeText(getParent(), getString(R.string.register_failed), Toast.LENGTH_LONG).show();
                    }
                }
        );
    }


    private void attemptUpdate(Bitmap headBitMap) {
        if (headBitMap != null) {

            String IMAGE_FILE_NAME = "temp_header.jpg";
            File headImageFile = BitmapUtils.saveBmpFile(headBitMap, IMAGE_FILE_NAME);

            TypedFile avatar = (headImageFile.equals("")) ? null : new TypedFile("image/jpg", headImageFile);
            UpdateAccountParams account = new UpdateAccountParams();
            account.mAccountId = AccountUtils.getAccountID();
            TypedString params = new TypedString(RestClient.getGson().toJson(account));
            RestClient.getRestService().update(avatar, params, new Callback<RestResponse>() {
                        @Override
                        public void success(RestResponse restResponse, Response response) {
                        }

                        @Override
                        public void failure(RetrofitError error) {

                        }
                    }
            );

        }
    }

    private void registerSuccess() {
        PersistUtils.savePersonCredential(personBean);
        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
        RegisterActivity.this.finish();
    }

    private void registerFailed() {
        PersistUtils.clearDatabase();
        LocalStorage.clearLocalStorage();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_button: {
                attemptRegister();
                break;
            }
        }
    }

    @OnClick(R.id.login)
    public void login(){
        finish();
    }
}
